package com.mzpai.web.onlineutil;

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.common.HybridBinarizer;
import com.mzpai.util.ChineseCharacterUtil;
import com.mzpai.util.StringUtils;

import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;

public class CsvUtils {
	
	/**
     * 从SN文件中读取内容（可读取某一列也可读取整行，根据需要调整逻辑）
     *
     * @param filePath 文件路径
     * @param encoding 编码方式
     * @return 返回SN集合
     */
    public static List<String> read(String filePath, String encoding) {
    	
    	//INSERT INTO `store_goods` VALUES ('1', 'B001', '皇冠', 'G001', '测试商品', null, null, null, null, null, null, null, '0.00', '0.00', null, null, null, null, null, null, null, null, null, null, null, null, '0.00');
    	//INSERT INTO `store_good_images` VALUES ('1', '1', 'G001', null, null);
    	String brandsql = "INSERT INTO eb_store_brand (brand_name, first_letter, brand_logo, brand_desc, site_url, sort_order, is_show, store_id, pet_cid, brand_cid) ";
    	String goodsql="";
    	
    	List<String> snList = new ArrayList<String>();
        try {
            // 创建CSV读对象
            CsvReader csvReader = new CsvReader(filePath, ',', Charset.forName(encoding));
            // 读表头
            csvReader.readHeaders();
            int count=0;
            String filePathsql="D://pythontest//sql//brand.txt";
            
            String leftImg="D:\\pythontest\\imgs\\dog\\zhuliang\\guochan\\left\\";
            String centerImg="D:\\pythontest\\imgs\\dog\\zhuliang\\guochan\\center\\";
            String fullPath=null;
            while (csvReader.readRecord()) {
            	String tiaoxingma=null;
                // 读一整行
//                System.out.println(csvReader.getRawRecord());
                // 读这行的某一列
                String spbh = csvReader.get("spbh").trim();//商品编号
                String pinpai = csvReader.get("pinpai").trim();//品牌
                String name = csvReader.get("name").trim();//商品名称
                String spjg = csvReader.get("spjg").trim();//商品价格
                String cszdj = csvReader.get("cszdj").trim();//厂商指导价
                String spguige = csvReader.get("spguige").trim();//商品规格
                String zhuyaoyuanliao = csvReader.get("zhuyaoyuanliao").trim();//主要原料
                String yingyangchenfen = csvReader.get("yingyangchenfen").trim();//营养成分
                String shiyongduixiang = csvReader.get("shiyongduixiang").trim();//适用对象
                String kelidaxiao = csvReader.get("kelidaxiao").trim();//颗粒大小
                String kouweipeifang = csvReader.get("kouweipeifang").trim();//口味配方
                String baozhiqi = csvReader.get("baozhiqi").trim();//出厂保质期
                String weight = csvReader.get("weight").trim();//重量
                String huaxianjia = csvReader.get("huaxianjia").trim();//划线价
                String url = csvReader.get("url").trim();//详细链接
//              if(StringUtils.isBlank(kouweipeifang)){
//                	System.out.println("获取内容为空");
//               }
                String str=ChineseCharacterUtil.convertHanzi2Pinyin(pinpai,false).toUpperCase();
                String first=str.substring(0,1);
                String valuestr="VALUES ('"+pinpai+"', '"+first+"', '', '', '', 0, 1, 3341, '', '');";
                
                
                
                
                writeStringToFile2(filePathsql,brandsql+valuestr);
                List<String> leftList=redaLeftImg(leftImg,spbh);
                List<String> centerList=redaLeftImg(centerImg,spbh);
                //左侧图读取条形码
                for(String leftstr:leftList){
                	fullPath=leftImg+leftstr;
                	tiaoxingma=decodeBarcode(fullPath);
        			if(!StringUtils.isNullOrBlank(tiaoxingma)){
        				break;
        			}
        		}
                if(StringUtils.isNullOrBlank(tiaoxingma)){
                	//中心图读取条码
                    for(String centerstr:centerList){
                    	fullPath=centerImg+centerstr;
                    	tiaoxingma=decodeBarcode(fullPath);
                    	if(!StringUtils.isNullOrBlank(tiaoxingma)){
            				break;
            			}
            		}
                }
                if(!StringUtils.isNullOrBlank(tiaoxingma)){
    				System.out.println("商品编号: "+spbh+ "图片路径: "+fullPath+"条形码: "+tiaoxingma);
    			}
                
//                System.out.println(spbh);
//                System.out.println(pinpai);
//                System.out.println(name);
//                System.out.println(spjg);
//                System.out.println(cszdj);
//                System.out.println(spguige);
//                System.out.println(zhuyaoyuanliao);
//                System.out.println(yingyangchenfen);
//                System.out.println(shiyongduixiang);
//                System.out.println(kelidaxiao);
//                System.out.println(kouweipeifang);
//                System.out.println(baozhiqi);
//                System.out.println(weight);
//                System.out.println(huaxianjia);
//                System.out.println(url);
                  System.out.println(tiaoxingma);
            }
            System.out.println("总条数: "+count);
        } catch (Exception e) {
        }
        return snList;
    }

    
    /**
     * 解析读取条形码
     * @param barcodePath 条形码文件路径
     * @return 
     */
    public static String decodeBarcode(String barcodePath){
        BufferedImage image;
        com.google.zxing.Result result = null;
        try {
            image = ImageIO.read(new File(barcodePath));
            if (image != null) {
                 LuminanceSource source = new BufferedImageLuminanceSource(image);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                result = new MultiFormatReader().decode(bitmap, null);
            }
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static List<String> redaLeftImg(String path,String spbh){
    	
    	List<String> leftList=new ArrayList<String>();
    	
    	File file = new File(path);
        File [] files = file.listFiles();
        for (int i = 0; i < files.length; i++){
            File file1 = files[i];
            String name=file1.getName();   //根据后缀判断
            if(name.contains(spbh)){
            	leftList.add(name);
            }
        }
        return leftList;
    }
    
 public static List<String> redaCenterImg(String path,String spbh){
    	List<String> centerList=new ArrayList<String>();
    	File file = new File(path);
        File [] files = file.listFiles();
        for (int i = 0; i < files.length; i++){
            File file1 = files[i];
            String name=file1.getName();   //根据后缀判断
            if(name.contains(spbh)){
            	centerList.add(name);
            }
        }
        return centerList;
    }
 
    
    
    public static void writeStringToFile2(String filePath,String txt) {
        try {
            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(txt);
            bw.write("\r\n");
            bw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 生成结果文件
     *
     * @param filePath 结果文件目录
     * @param encoding 编码方式
     * @param headers  表头内容
     * @param dataList 数据集合
     */
    public static void write(String filePath, String encoding, String[] headers, List<String[]> dataList) {
        try {
            File file = new File(filePath).getParentFile();
            if (!file.exists()) {
                file.mkdirs();
            }
            // 创建CSV写对象
            CsvWriter csvWriter = new CsvWriter(filePath, ',', Charset.forName(encoding));
            // 写表头
            if (headers != null && headers.length > 0) {
                csvWriter.writeRecord(headers);
            }
            if (dataList != null && dataList.size() > 0) {
                for (String[] content :
                        dataList) {
                    csvWriter.writeRecord(content);
                }
            }
            csvWriter.close();
        } catch (Exception e) {
        }
    }

}
